﻿// CInputDlg.cpp: 实现文件
//

#include "pch.h"
#include "CClient.h"
#include "CInputDlg.h"
#include "afxdialogex.h"
#include "CWorkerDlg.h" // 具体使用时再引入头文件

// CInputDlg 对话框

IMPLEMENT_DYNAMIC(CInputDlg, CDialogEx)

// 参数一：模板资源ID； IDD dialog ID；IDC Control ID
// 参数二：传入父窗口的指针，就不能点击当前窗口的父窗口了
// explicit CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);

CInputDlg::CInputDlg(CWorkerDlg* pDlg, CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_INPUT, pParent)
	, m_pDlg(pDlg)
{

}

CInputDlg::~CInputDlg()
{
}

void CInputDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}


BEGIN_MESSAGE_MAP(CInputDlg, CDialogEx)
	ON_BN_CLICKED(IDC_INPUT_ADD, &CInputDlg::OnClickedInputAdd)
	ON_BN_CLICKED(IDC_INPUT_CANCEL, &CInputDlg::OnClickedInputCancel)
END_MESSAGE_MAP()


// CInputDlg 消息处理程序


void CInputDlg::OnClickedInputAdd()
{
	CWnd* pWnd = GetFocus();// 获取焦点所在窗口
	int id = pWnd->GetDlgCtrlID();// 获取焦点所在控件
	if (id == IDC_INPUT_DATE || id == IDC_INPUT_ADD) {// 如果是日期或添加
		InsertData();
	}
	else {
		NextDlgCtrl();// 跳转下个焦点
	}
}

void CInputDlg::InsertData()
{

	if (MessageBox(_T("确定插入吗"), _T("提示"), MB_YESNO) == IDNO) {
		return;
	}

	CString str;
	SInfo d;
	GetDlgItemText(IDC_INPUT_NUM, str);
	d.nNumb = _tstoi(str);
	GetDlgItemText(IDC_INPUT_NAME, str);
	std::string s = theApp.UnicodeToUTF8(str);
	strcpy_s(d.sName, _countof(d.sName), s.c_str());// 安全版strcpy
	GetDlgItemText(IDC_INPUT_SALARY, str);
	d.fSala = _tstof(str);
	GetDlgItemText(IDC_INPUT_DATE, str);
	s = theApp.UnicodeToUTF8(str);
	strcpy_s(d.sDate, _countof(d.sDate), s.c_str());

	if (FindNum(d)) {
		MessageBox(_T("工号已存在"), _T("提示"), MB_OK);
		return;
	}

	int cmd = WK_INPUT;
	theApp.m_sock.Send(&cmd, sizeof(cmd));
	theApp.m_sock.Send(&d, sizeof(d));

	// 清理
	SetDlgItemText(IDC_INPUT_NUM, CString());
	SetDlgItemText(IDC_INPUT_NAME, CString());
	SetDlgItemText(IDC_INPUT_SALARY, CString());
	SetFocus();

	m_pDlg->Refresh();
}

// 默认按钮IDOK点击事件也一样
void CInputDlg::OnOK()
{
	// 接收回车键回调
	OnClickedInputAdd();

	// CDialogEx::OnOK();
}

BOOL CInputDlg::FindNum(SInfo& d)
{
	int cmd = WK_FIND_NUMB;
	theApp.m_sock.Send(&cmd, sizeof(cmd));
	theApp.m_sock.Send(&d.nNumb, sizeof(d.nNumb));
	int count = 0;
	if (theApp.m_sock.Receive(&count, sizeof(count)) != sizeof(count)) {
		return FALSE;
	}
	if (count < 1) {
		return FALSE;
	}
	return theApp.m_sock.Receive(&d, sizeof(d)) == sizeof(d);
}


BOOL CInputDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	GetDlgItem(IDC_INPUT_ADD)->SetFocus();

	return FALSE;
}


void CInputDlg::OnClickedInputCancel()
{
	EndDialog(IDCANCEL);
}
